package cn.itcast.user.web;

import cn.itcast.user.config.PatternProperties;
import cn.itcast.user.pojo.User;
import cn.itcast.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

@Slf4j
@RestController
@RequestMapping("/user")
@RefreshScope   //配置热更新
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PatternProperties patternProperties;
    /**
     * 根据id查询用户
     * 路径： /user/110
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id,
                          @RequestHeader(value = "Truth", required = false)String truth)
            throws InterruptedException {
        if (id == 1) {
            //id为1时触发慢调用
            Thread.sleep(60L);
        } else if (id == 2) {
            throw new RuntimeException("故意抛出异常，触发异常比例熔断。。。");
        }
        log.info("truth:{}", truth);
        return userService.queryById(id);
    }

    /**
     * 注入nacos中配置属性：日期格式模板
     */
    @Value("${pattern.dateformat}")
    private String dateformat;

    /**
     * 按照给定模板返回当前时间
     * @return
     */
    @GetMapping("/now1")
    public String now1() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat, Locale.CHINA));
    }

    /**
     * 按照给定模板返回当前时间
     * @return
     */
    @GetMapping("/now2")
    public String now2() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateformat()));
    }

    /**
     * nacos多环境配置测试接口
     * @return
     */
    @GetMapping("prop")
    public PatternProperties prop() {
        return patternProperties;
    }
}
